package cron_job

import (
	"context"
	"github.com/spf13/cast"
	"log"
	redis "nearby/biz/dal/cache"
	"nearby/biz/service"
)

type SyncMomentViewCntTask struct {
}

func (t SyncMomentViewCntTask) Handle() {
	// 设计方案见文档链接中, 关于统计帖子的浏览量部分
	// https://tarplkpqsm.feishu.cn/docs/doccn12wylGEp4gfy5hw06cXNLc
	ctx := context.Background()
	size := int64(50)
	n := 500
	log.Printf("SyncMomentViewCntTask开始")
	for i := 0; i < n; i++ {
		scanRes := redis.HScan(ctx, redis.ViewMomentKey, 0, "", size)
		keys, cursor, err := scanRes.Result()
		if err != nil {
			log.Printf("SyncMomentViewCntTask report, redis.HScan fial, err is %+v", err)
		}
		if len(keys) == 0 {
			break
		}
		for j := 0; j < len(keys); j += 2 {
			momentId := keys[j]
			incr := keys[j+1]
			ss := service.ViewMomentDetailService{}
			err = ss.SyncViewCnt(ctx, cast.ToInt64(momentId), cast.ToInt64(incr))
			if err != nil {
				log.Printf("SyncViewCnt fail, err: %+v", err)
			}
		}
		err = redis.HDel(ctx, redis.ViewMomentKey, keys...).Err()
		if err != nil {
			log.Printf("SyncMomentViewCntTask report, redis.HDel fail, err: %+v", err)
		}
		if cursor == 0 {
			break
		}
	}
	log.Printf("SyncMomentViewCntTask结束")
}

func (SyncMomentViewCntTask) Spec() string {
	// 5min更新一次, 这个时间是找PM申壮拍的
	return "@every 5m"
}

func (SyncMomentViewCntTask) SpecDebugMode() string {
	return "@every 5m"
}
